package com.example.controller;

import com.example.entity.Organization;
import com.example.entity.Users;
import com.example.entity.Volunteer;
import com.example.service.UsersService;
import com.example.service.VolunteerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;
import java.util.Date;
import com.example.dao.UsersDao;
import com.example.entity.Activity;
import com.example.service.ActivityService;
@Controller
@RequestMapping("/users")
public class UsersContoller {

    @Autowired
    private UsersService usersService;

    @GetMapping("/list")
    public String list(Model model) {
        List<Users> users = usersService.getAllUsers();
        model.addAttribute("users", users);
        return "users/list";
    }
    @GetMapping("/add")
    public String toAddPage() {
        return "users/add";
    }

    @PostMapping("/add")
    public String add(Users users) {
        usersService.addUsers(users);
        return "redirect:/users/list";
    }

    @GetMapping("/edit/{userid}")
    public String toEditPage(@PathVariable("userid") Integer userid, Model model) {
        Users users = usersService.getUsersById(userid);
        model.addAttribute("users", users);
        return "users/edit";
    }

    @PostMapping("/edit")
    public String edit(Users users) {
        usersService.updateUsers(users);
        return "redirect:/users/list";
    }

    @GetMapping("/delete/{userid}")
    public String delete(@PathVariable("userid") Integer userid) {
        usersService.deleteUsers(userid);
        return "redirect:/users/list";
    }

    @GetMapping("/search")
    public String searchUsers(
            @RequestParam(required = false) String usernumber,
            @RequestParam(required = false) String usertype,
            Model model) {

        // 构建查询条件
        // 查询用户列表
        List<Users> users ;
        if (StringUtils.hasText(usernumber) || StringUtils.hasText(usertype)){

            users = usersService.searchUsers(usernumber, usertype);

        }else {
            // 获取所有用户
            users = usersService.getAllUsers();
        }
        model.addAttribute("users", users);
        model.addAttribute("usernumber", usernumber);
        model.addAttribute("usertype", usertype);
        return "/users/list"; // 返回用户列表页面
    }


    @RequestMapping("login")

    public ModelAndView login(String usernumber, String password, HttpServletRequest request) {
        ModelAndView mv = new ModelAndView();
      int volunteer_id=1;
        final Users users = this.usersService.getUsersByUserNumberAndPassword(usernumber, password); // 查询用户信息
        System.out.println("查询结果 users: " + users); // 打印日志

        if (users == null) {
            mv.setViewName("../../index"); // 登录失败跳回首页
        } else {
            HttpSession session = request.getSession();
            session.setAttribute("users", users); // 将用户信息存入 Session

            // 获取机构信息
            Organizations organizations = this.usersDao.findOrganizationInfoByUserId(users.getUserid());
            session.setAttribute("organizations", organizations);

            System.out.println("获取到的机构信息: " + organizations); // 日志输出
            if (organizations != null) {
                session.setAttribute("organizations", organizations);
                System.out.println("机构姓名: " + organizations.getOrgName()); // 日志输出
            }

            // 根据用户类型跳转不同页面
            if ("admin".equals(users.getUsertype())) {
                mv.setViewName("redirect:/users/list");
            } else if ("organization".equals(users.getUsertype())) {
                mv.setViewName("organization/home");

                Organizations org = this.usersDao.findOrganizationInfoByUserId(users.getUserid());
                int activityCount = activityService.countActivitiesByOrgId(org.getOrgid());

                // 将数据存储到 Session 或 Model
                session.setAttribute("activityCount", activityCount);

            } else {
                mv.setViewName("redirect:/volunteer/list");
            }
        }

        return mv;
    }
    // 新增注册页面跳转和注册处理逻辑
    @GetMapping("register")
    public String showRegister() {
        return "../../register"; // 返回 register.jsp 页面
    }

    @PostMapping("register")
    public ModelAndView register(
            @RequestParam String usernumber,
            @RequestParam String password,
            @RequestParam String usertype,

            // 志愿者字段
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String sex,
            @RequestParam(required = false) String birthdate,
            @RequestParam(required = false) String profession,
            @RequestParam(required = false) String skills,
            @RequestParam(required = false) String experience,
            @RequestParam(required = false) String phone,

            // 机构字段
            @RequestParam(required = false) String org_name,
            @RequestParam(required = false) String org_type,
            @RequestParam(required = false) String contact_phone,
            @RequestParam(required = false) String address,
            @RequestParam(required = false) String description,
            @RequestParam(required = false) String logo) {

        ModelAndView mv = new ModelAndView();

        // 保存用户基础信息
        Users newUser = new Users();
        newUser.setUsernumber(usernumber);
        newUser.setPassword(password);
        newUser.setUsertype(usertype);

        boolean userSaved = usersService.registerUser(newUser);

        if (!userSaved) {
            mv.addObject("error", "注册失败，请重试");
            mv.setViewName("../../register");
            return mv;
        }

        // 查询刚插入的用户ID
        Users createdUser = usersService.getUsersByUserNumberAndPassword(usernumber, password);
        if (createdUser == null) {
            mv.addObject("error", "注册失败，请重试");
            mv.setViewName("../../register");
            return mv;
        }
   // 查询刚插入的用户ID
        Users createdUser = usersService.getUsersByUserNumberAndPassword(usernumber, password);
        int userId = createdUser.getUserid();

        // 根据用户类型保存扩展信息
        if ("volunteer".equals(usertype)) {
            Volunteer volunteer = new Volunteer();
            volunteer.setUserid(createdUser.getUserid());
            volunteer.setName(name);
            volunteer.setSex(sex);
            volunteer.setBirthdate(birthdate);
            volunteer.setProfession(profession);
            volunteer.setSkills(skills);
            volunteer.setExperience(experience);
            volunteer.setPhone(phone);
            usersService.registerVolunteer(volunteer); // 注册志愿者

            mv.setViewName("redirect:../index.jsp");

        } else if ("organization".equals(usertype)) {
            Organizations organization = new Organizations();
            organization.setUserid(createdUser.getUserid());
            organization.setOrgName(org_name);
            organization.setOrgType(org_type);
            organization.setContactPhone(contact_phone);
            organization.setAddress(address);
            organization.setDescription(description);
            organization.setLogo(logo);
            usersService.registerOrganization(organization); // 注册机构

            mv.setViewName("redirect:../index.jsp");
        }

        return mv;
    }

    }
  @GetMapping("/organization/addactivity")
    public String showAddActivityForm() {
        return "organization/addactivity"; // 跳转到 addactivity.jsp 页面
    }
    /**
     * 创建新活动。
     *
     * @param formData 表单提交的数据
     * @param session  当前会话
     * @return 重定向到活动管理页面
     */
     @PostMapping("/organization/addactivity")
    public String createActivity(@RequestParam Map<String, String> formData, HttpSession session) {
        Organizations org = (Organizations) session.getAttribute("organizations"); // 获取当前机构信息
        if (org == null) {
            return "redirect:/users/login";
        }

        Activity activity = new Activity(); // 创建活动对象
        activity.setOrgid(org.getOrgid());
        activity.setTitle(formData.get("title"));
        activity.setCoverImage(formData.get("cover_image"));
        activity.setDescription(formData.get("description"));
        activity.setStartTime(formData.get("start_time"));
        activity.setEndTime(formData.get("end_time"));
        activity.setRegistrationDeadline(formData.get("registration_deadline"));
        activity.setLocation(formData.get("location"));

        activity.setStatus("未开始"); // 设置状态
        activity.setIsApproved("待审核"); // 设置审核状态

        activity.setCreateTime(new Date()); // 设置创建时间
        activity.setUpdateTime(new Date()); // 设置更新时间

        activityService.createActivity(activity); // 调用服务层保存活动

        return "redirect:/organization/guanli"; // 返回活动管理页面
    }

}
